import * as faceapi from "face-api.js";

main()

let faceMatcher = null
const classes = ['amy', 'bernadette', 'howard', 'leonard', 'penny', 'raj', 'sheldon', 'stuart']
let currClassIdx = 0
let currImageIdx = 1

async function main(){
    // load model
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')

    faceMatcher = await createBbtFaceMatcher(1)
    runFaceRecognition()

    closeLoading()
}

// 开始识别每一张图片
async function runFaceRecognition(){
    let uri = getImageUri(classes[currClassIdx], currImageIdx)
    const input = await faceapi.fetchImage(uri)
    const imgEl = document.getElementById('face')
    imgEl.src = input.src

    const ts = Date.now()
    const descriptor = await faceapi.computeFaceDescriptor(input)
    const bestMath = faceMatcher.findBestMatch(descriptor)

    const prediction = document.getElementById('prediction')
    prediction.value = bestMath.toString()
    const time = document.getElementById('time')
    time.value = Date.now() - ts +'ms'

    if(currImageIdx===5){
        currClassIdx = currClassIdx === classes.length-1?0:currClassIdx+1
    }
    currImageIdx = currImageIdx===5?1:currImageIdx+1
    
    setTimeout(runFaceRecognition, 1000)
}

// 获取图片
function getImageUri(className,num){
    return 'http://127.0.0.1:8888/images/'+className+'/'+className+num+'.png'
}


// 获取face样本特征，提取每个人的第一张图片作为样本
async function createBbtFaceMatcher(num){

    const labeledFaceDescriptors = await Promise.all(classes.map(async className=>{
        let uri = getImageUri(className, num)
        const img = await faceapi.fetchImage(uri)
        const descriptors = [await faceapi.computeFaceDescriptor(img)]        
        return new faceapi.LabeledFaceDescriptors(className, descriptors)
    }))

    return new faceapi.FaceMatcher(labeledFaceDescriptors)
}